package com.stylefeng.guns.modular.util;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件工具类
 * 
 * @author liqi
 *
 */
public class FileUtil {


	/**
	 * 文件读取
	 * 
	 * @param inputStr
	 *            文件路径
	 * @return List<String>
	 */
	public static List<String> read(String inputStr) {
		BufferedReader inputBR = null;
		try {
			inputBR = new BufferedReader(new FileReader(inputStr));
			String lineStr = "";
			List<String> dataList = new ArrayList<>();
			while ((lineStr = inputBR.readLine()) != null) {
				dataList.add(lineStr);
			}
			return dataList;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputBR != null) {
					inputBR.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 文件读写
	 * 
	 * @param dataList
	 *            文件内容
	 * @param outputStr
	 *            文件路径
	 * @param isAdd
	 *            是否追加
	 */
	public static void write(List<String> dataList, String outputStr, boolean isAdd) {
		BufferedWriter outputBW = null;
		try {
			File outputFile = new File(outputStr);
			if (!outputFile.exists()) {
				outputFile.createNewFile();
			}
			outputBW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile, isAdd), "UTF-8"));// true为追加写入
			for (String dataStr : dataList) {
				outputBW.write(dataStr + "\n");
				outputBW.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (outputBW != null)
					outputBW.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static boolean download(String fileName, List<String> dataList, HttpServletResponse response) {
		response.setContentType("application/force-download");
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			for (String data : dataList) {
				os.write((data+"\n").getBytes());
			}
			os.flush();
			os.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}